<!-- eslint-disable vue/no-static-inline-styles -->
<!--
 * @Author: Junxu
 * @Date: 2024-07-18 13:55:29
 * @LastEditors: Junxu
 * @LastEditTime: 2024-08-01 08:43:35
 * @Description: 维修报告确认
-->
<template>
 <view class="report-edit">
      <view class="report-edit-msg-box" v-if="showMsg">
        <view class="report-edit-msg">
          <view class="content">
            维修完成后将发送“故障维修报告”至客户微信群，请确认报告无误后进行发送
          </view>
          <view class="close" @click="showMsg = false">
            <view class="icon-close"></view>
          </view>
        </view>
      </view>
      <view class="report-edit-content">
        <view class="top-card">
          <view class="top-card-title">电梯故障维修报告</view>
          <view class="top-card-content">
            <view>尊敬的客户：</view>
            <view
              >您好！以下是关于本次电梯故障的维修报告，我们力求以最简单明了的方式，让您了解故障的全貌及我们的处理过程。</view
            >
          </view>
          <view class="top-card-pic">
            <image
             src="./static/report_pic.png"
              mode="widthFix"
              style="width: 176rpx"
            ></image>
          </view>
        </view>
        <view class="report-card">
          <view class="report-card-title"
            ><view class="text">电梯基本信息</view></view
          >
          <view class="row">
            <view class="title">电梯名称</view>
            <view class="content"
              >{{ info.buildingName }} {{ info.elevatorAddress }}</view
            >
          </view>
          <view class="row">
            <view class="title">电梯品牌</view>
            <view class="content">{{ info.brandName || '--' }}</view>
          </view>
          <view class="row">
            <view class="title">额定载重</view>
            <view class="content">{{ info.supportingPower ? info.supportingPower+'kg' : '--' }}</view>
          </view>
          <view class="row">
            <view class="title">额定速度</view>
            <view class="content">{{ info.speed ? info.speed+'m/s' : '--' }}</view>
          </view>
        </view>
        <view class="report-card">
          <view class="report-card-title"
            ><view class="text">故障现象与原因</view></view
          >
          <view class="row">
            <view class="title">报障时间</view>
            <view class="content">{{ info.planCreateTime }}</view>
          </view>
          <view class="part-card" v-for="(item, i) in info.reasonList" :key="i">
            <view class="part-card-title">
              <view class="serial-num">{{ i + 1 }}</view>
              <view class="content">{{
                item.partsNames | replaceAmpersand
              }}
              <text v-if="item.floorStandNames">({{ item.floorStandNames.replaceAll(',','>') }})</text>  
            </view>
            </view>
            <view class="part-card-content">
              <view class="row">
                <view class="title">现象</view>
                <view class="content">
                  <view
                    class="textarea-box"
                    :style="{
                      borderColor: formError.includes('mfDesc') && !item.mfDesc
                        ? '#e02020'
                        : '',
                    }"
                  >
                    <textarea
                      v-model="item.mfDesc"
                      placeholder="示例：厅门无法正常闭合"
                      placeholder-class="textare"
                      style="font-size: 28rpx; height: 120rpx; width: 100%"
                      maxlength="300"
                      :always-embed="true"
                    />
                    <view class="length">{{
                      (item.mfDesc ? item.mfDesc.length : "0") + "/300"
                    }}</view>
                  </view>
                  <view
                    v-if="formError.includes('mfDesc') && !item.mfDesc"
                    style="color: #e02020; font-size: 24rpx"
                    >请输入故障描述</view
                  >
                </view>
              </view>
              <view class="row">
                <view class="title">原因</view>
                <view class="content">
                  <!-- <view>
                    <view class="select-box">
                      <view
                        class="select"
                        :class="{
                          selected: item.faultReason.includes(reason.dictValue),
                        }"
                        v-for="reason in reasonList"
                        :key="reason.id"
                        >{{ reason.dictValue }}</view
                      >
                    </view>
                  </view> -->
                  <!-- 其他原因文本输入 -->
                  <view
                    class="textarea-box"
                    :style="{
                      borderColor: formError.includes('faultReason') && !item.faultReason
                        ? '#e02020'
                        : '',
                    }"
                  >
                    <textarea
                      v-model="item.faultReason"
                      placeholder="示例：厅门地坎卡了碎石，导致厅门无法闭合"
                      placeholder-class="textare"
                      style="font-size: 28rpx; height: 80rpx; width: 100%"
                      maxlength="300"
                      :always-embed="true"
                    />
                    <view class="length">{{
                      (item.faultReason ? item.faultReason.length : "0") +
                      "/300"
                    }}</view>
                  </view>
                  <view
                    v-if="formError.includes('faultReason') && !item.faultReason"
                    style="color: #e02020; font-size: 24rpx"
                    >请输入故障原因</view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="report-card">
          <view class="report-card-title"
            ><view class="text">故障处理方案</view></view
          >
          <view
            class="part-card"
            v-for="(item, i) in info.projectList"
            :key="i"
          >
            <view class="part-card-title">
              <view class="serial-num">{{ i + 1 }}</view>
              <view class="content">{{
                item.partsNames | replaceAmpersand
              }}
                <text v-if="item.floorStandNames">({{ item.floorStandNames.replaceAll(',','>') }})</text>
            </view>
            </view>
            <view class="part-card-content">
              <view class="row">
                <view class="title">方案</view>
                <view class="content">
                  <view
                    class="textarea-box"
                    :style="{
                      borderColor: formError.includes('faultDesc') && !item.faultDesc
                        ? '#e02020'
                        : '',
                    }"
                  >
                    <textarea
                      v-model="item.faultDesc"
                      placeholder="示例：厅门无法正常闭合"
                      placeholder-class="textare"
                      style="font-size: 28rpx; height: 120rpx; width: 100%"
                      maxlength="300"
                      :always-embed="true"
                    />
                    <view class="length">{{
                      (item.faultDesc ? item.faultDesc.length : "0") + "/300"
                    }}</view>
                  </view>
                  <view
                    v-if="formError.includes('faultDesc') && !item.faultDesc"
                    style="color: #e02020; font-size: 24rpx"
                    >请输入处理方案</view>
                </view>
              </view>
              <view class="row">
                <view class="title" style="flex: 0 0 140rpx">配件更换</view>
                <view class="content">
                  <view>
                    <view class="select-box">
                      <view
                        class="select"
                        style="margin-bottom: 0"
                        :class="{
                          selected: item.partsOpe === part.value,
                        }"
                        v-for="part in partList"
                        :key="part.value"
                        @click="handleChangeSelect(part, 'partsOpe', item)"
                        >{{ part.label }}</view
                      >
                    </view>
                  </view>
                </view>
              </view>
              <view class="column" style="padding-top: 16rpx">
                <view class="title">处理前图片</view>
                <view class="content">
                  <view>
                    <image-drag-sort
                      tips="上传图片"
                      :max="9"
                      @changeList="(val) => handelChangeFile(val, 'mfImgUrl', i)"
                      :list="item.mfImgUrl"
                    >
                    </image-drag-sort>
                  </view>
                  <view
                    v-if="formError.includes('mfImgUrl') && item.mfImgUrl.length === 0"
                    style="color: #e02020; font-size: 24rpx"
                    >请选择处理前图片</view>
                </view>
              </view>
              <view class="column">
                <view class="title">处理后图片</view>
                <view class="content">
                  <view>
                    <image-drag-sort
                      tips="上传图片"
                      :max="9"
                      @changeList="(val) => handelChangeFile(val, 'faultImg', i)"
                      :list="item.faultImg"
                    >
                    </image-drag-sort>
                  </view>
                  <view
                    v-if="formError.includes('faultImg') && item.faultImg.length === 0"
                    style="color: #e02020; font-size: 24rpx"
                    >请选择处理后图片</view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <div class="report-card">
          <div class="report-card-title">
            <div class="text">维保人员</div>
          </div>
          <div class="row">
            <div class="title">姓名</div>
            <div class="content">{{ info.planUserName }}</div>
          </div>
          <!-- <div class="row">
            <div class="title">报告日期</div>
            <div class="content">2023-02-04 10:00:00</div>
          </div> -->
        </div>
        <view class="report-edit-info">
          感谢贵方选择使用我司提供的产品和服务，我们将持续提供专业、高效的服务，确保您的电梯运行无忧。
        </view>
      </view>
      <view class="report-edit-footer">
        <view class="btn-box">
          <view class="btn" @click="onSubmit">生成报告并发送</view>
        </view>
      </view>
    </view>
</template>
  
<script>
import ImageDragSort from '@/components/image-drag-sort/img-and-video.vue';
import { mapState } from 'vuex';
import {
	getReportInfoByRepairPlan,
	addOrUpdateReport,
	sendReport,
	getReportDetail,
} from '@/apis/repair.js';

export default {
	name: 'ReportEdit',
	components: {
		ImageDragSort,
	},
	filters: {
		replaceAmpersand(value) {
			if (!value) return '';
			return value.replace(/&amp;&amp;/g, '>');
		},
	},
	data() {
		return {
			planId: '',
			reasonList: [],
			otherId: '',
			partSelected: null,
			partList: [
				{
					value: 1,
					label: '无需更换',
				},
				{
					value: 2,
					label: '建议更换',
				},
				{
					value: 3,
					label: '已更换',
				},
			],
			showMsg: true,
			info: {
				id: null,
				createUser: null,
				createDept: null,
				createTime: null,
				updateUser: null,
				updateTime: null,
				status: null,
				isDeleted: null,
				tenantId: null,
				planId: null,
				elevatorId: null,
				buildingId: null,
				elevatorAddress: null,
				buildingName: null,
				brandName: null,
				supportingPower: null,
				speed: null,
				sendStatus: null,
				reportData: [],
				reportFile: null,
				reportImg: null,
				planUserName: null,
				planCreateTime: null,
				planFinishTime: null,
				workOrderType: null,
				reportUserName: null,
				reportUserRole: null,
				reasonList: [],
				projectList: [],
			},
			reportId: null,
			formError: [],
		};
	},
	onLoad(e) {
		const { planId, reportId } = e;
		if (planId) {
			this.planId = planId;
			this.getDetail();
		} else if (reportId) {
			this.reportId = reportId;
			this.getDetail();
		}
	},
	computed: {
		...mapState('user', ['userinfo']),
	},
	mounted() {
		wx.enableAlertBeforeUnload({
			message: '检测到尚未发送维修报告，请确认报告无误后立即发送',
			success: (res) => {
				console.log(res, 'enableAlertBeforeUnload-res');
			},
			fail: (err) => {
				console.log(err, 'enableAlertBeforeUnload-err');
			},
		});
	},
	onUnload() {
		// 卸载返回提示
		wx.disableAlertBeforeUnload({
			success: (res) => {
				console.log(res, 'disableAlertBeforeUnload-res');
			},
			fail: (err) => {
				console.log(err, 'disableAlertBeforeUnload-err');
			},
		});
	},
	methods: {
		async getDetail() {
			uni.showLoading({
				title: '加载中',
			});
			try {
				let param = {
					planId: this.planId,
				};
				let getDetailPromise = getReportInfoByRepairPlan;
				if (this.reportId) {
					param = {
						id: this.reportId,
					};
					getDetailPromise = getReportDetail;
				}
				const res = await getDetailPromise(param);
				console.log(res, 'res');
				if (res && res.code == 200 && res.data) {
					let reasonList = [];
					let projectList = [];
					if (res.data.reportData) {
						if (!Array.isArray(res.data.reportData)) {
							res.data.reportData = JSON.parse(res.data.reportData);
						}
						res.data.reportData.forEach((item) => {
							// item.partsNames = item.partsNames.replace(new RegExp('&','g'),"&");
							// item.partsNames = item.partsNames.replaceAll("&amp;&amp;", ">");
							reasonList.push({
								mfDesc: item.mfDesc,
								partsNames: item.partsNames,
								partsIds: item.partsIds,
								faultReason: item.faultReason,
								floorStandNames:item.floorStandNames,
							});
							projectList.push({
								faultDesc: item.faultDesc,
								faultImg: item.faultImg || [],
								mfImgUrl: item.mfImgUrl || [],
								partsNames: item.partsNames,
								partsIds: item.partsIds,
								partsOpe: item.partsOpe || 1,
								floorStandNames:item.floorStandNames,
							});
						});
					}
					console.log(reasonList, 'reasonList');
					res.data.reasonList = reasonList;
					res.data.projectList = projectList;
					this.info = res.data;
				}
				uni.hideLoading();
			} catch (error) {
				uni.hideLoading();
				console.log(error);
			}
		},
		handelChangeFile(val, key, index) {
			let item = this.info.projectList[index];
			console.log(val, 'val的值');
			item[key] = val;
			console.log(item, 'item');
			console.log(this.info, 'info');
		},
		showSubmitMsg() {
			return new Promise((resolve, reject) => {
				uni.showModal({
					title: '维修报告发送提醒',
					content:
            '是否确认报告内容无误？报告发送后将无法撤销更改，请谨慎操作',
					cancelText: '暂不发送',
					cancelColor: '#999999',
					confirmColor: '#0091ff',
					confirmText: '发送报告',
					success: function (res) {
						if (res.confirm) {
							resolve(true);
						} else {
							resolve(false);
							// uni.showModal({
							//   title: "维修报告发送提醒",
							//   content:
							//     "检测到尚未发送维修报告，请确认报告无误后立即发送，否则系统将在10分钟后自动发送。",
							//   cancelText: "取消",
							//   cancelColor: "#999999",
							//   confirmColor: "#0091ff",
							//   confirmText: "确认发送",
							//   success: function (res2) {
							//     if (res2.confirm) {
							//       console.log("用户点击确定");
							//       resolve(true);
							//     } else {
							//       resolve(false);
							//       console.log("用户点击取消");
							//     }
							//   },
							// });
						}
					},
					fail: function (err) {
						reject(err || new Error('User canceled the operation.'));
					},
				});
			});
		},
		handleChangeSelect(val, type, item) {
			if (type === 'partsOpe') {
				item.partsOpe = val.value;
			}
		},
		async onSendReport(reportId) {
			try {
				uni.showLoading({
					title: '报告发送中',
				});
				const res = await sendReport({ reportId });
				uni.hideLoading();
				// console.log(res, "res");
				// if (res.code == 200 && res.data) {
				//   uni.showToast({
				//     title: "报告已发送至客户",
				//     icon: "none",
				//   });
				// } else {
				//   uni.showToast({
				//     title: "维修报告发送失败",
				//     icon: "none",
				//   });
				// }
			} catch (error) {
				uni.hideLoading();
				// uni.showToast({
				//   title: "维修报告发送失败",
				//   icon: "none",
				// });
				console.log(error, 'onSendReport');
			}
		},
		async onSubmit() {
			this.formError = [];
			let msg = [];
			for (const item of this.info.reasonList) {
				if (!item.mfDesc) {
					this.formError.push('mfDesc');
					msg.push('故障现象');
				}
				if (!item.faultReason) {
					this.formError.push('faultReason');
					msg.push('故障原因');
				}
			}
			for (const item of this.info.projectList) {
				if (!item.faultDesc) {
					this.formError.push('faultDesc');
					msg.push('处理方案');
				}
				if (item.mfImgUrl.length === 0) {
					this.formError.push('mfImgUrl');
					msg.push('处理前图片'); 
				}
				if (item.faultImg.length === 0) {
					this.formError.push('faultImg');
					msg.push('处理后图片');
				}
			}
			if (msg.length !== 0) {
				uni.showToast({
					title: '请填写' + msg.join('、'),
					icon: 'none',
				});
				return;
			}
			try {
				const flag = await this.showSubmitMsg();
				if (flag) {
					const param = JSON.parse(JSON.stringify(this.info));
					let reportData = [];
					param.reasonList.forEach((item, i) => {
						let item2 = param.projectList[i];
						reportData.push({
							mfDesc: item.mfDesc,
							partsIds: item.partsIds,
							faultReason: item.faultReason,
							faultDesc: item2.faultDesc,
							faultImg: item2.faultImg,
							mfImgUrl: item2.mfImgUrl,
							partsNames: item2.partsNames,
							floorStandNames: item2.floorStandNames,
							floorStandIds: item2.floorStandIds,
							partsOpe: item2.partsOpe,
						});
					});
					param.reportData = reportData;
					delete param.projectList;
					delete param.reasonList;
					// const { reasonList, projectList, reportData, ...param } = this.info;
					// let reportDataList = [];
					// reasonList.forEach((item, i) => {
					//   let item2 = projectList[i];
					//   let faultImg = item2.faultImg.map((v) => {
					//     return {
					//       url: v.url,
					//       type: v.type,
					//     };
					//   });
					//   let mfImgUrl = item2.mfImgUrl.map((v) => {
					//     return {
					//       url: v.url,
					//       type: v.type,
					//     };
					//   });
					//   reportDataList.push({
					//     mfDesc: item.mfDesc,
					//     mfImgUrl: item2.mfImgUrl,
					//     partsNames: item.partsNames,
					//     partsIds: item.partsIds,
					//     faultReason: item.faultReason,
					//     faultDesc: item2.faultDesc,
					//     faultImg: faultImg,
					//     mfImgUrl: mfImgUrl,
					//     partsNames: this.replaceAmpersand(item2.partsNames),
					//     partsOpe: item2.partsOpe,
					//   });
					// });
					// param.reportData = reportDataList;
					param.reportUserRole = this.userinfo.fullRoleName;
					param.reportUserName = this.userinfo.nick_name;
					console.log(param, 'param');
					uni.showLoading({
						title: '提交维修报告中',
					});
					const res = await addOrUpdateReport(param);
					uni.hideLoading();
					if (res && res.code == 200 && res.data) {
						console.log(res, 'res');
						this.onSendReport(res.data);
						setTimeout(() => {
							// #ifdef H5
							uni.redirectTo({
								url: '/subpages/repair/reportDetailH5?id=' + res.data,
							});
							// #endif
							// #ifndef H5
							uni.redirectTo({
								url: '/subpages/repair/reportDetail?id=' + res.data,
							});
							// #endif
						}, 500);
					}
				}
			} catch (error) {}
		},
	},
};
</script>
  
<style lang="scss" scoped>
view {
  box-sizing: border-box;
}
.report-edit {
  .report-edit-msg-box {
    height: 112rpx;
    width: 100%;
  }
  &-msg {
    width: 100%;
    height: 112rpx;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 3;
    display: flex;
    align-items: center;
    // padding: 20rpx;
    padding: 0 20rpx;
    background: #fffadf;
    .content {
      flex: 1;
      width: 0;
      padding: 0 20rpx;
      font-size: 28rpx;
      color: #ff7505;
      font-size: 13px;
      line-height: 36rpx;
    }
    .close {
      //   width: 32rpx;
      //   height: 32rpx;
      margin-left: 30rpx;
    }
  }
  &-content {
    padding: 20rpx;
    background-color: #e2f3ff;
    .top-card {
      background-color: #fff;
      padding: 40rpx;
      border-radius: 8rpx;
      position: relative;
      margin-bottom: 16rpx;
      &::before,
      &::after {
        content: "";
        position: absolute;
        width: 20rpx; // 半圆的直径
        height: 20rpx;
        border-radius: 50%; // 创建圆形
        background-color: #e2f3ff;
      }

      &::before {
        left: -10rpx;
        top: 110rpx;
      }

      &::after {
        right: -10rpx;
        top: 110rpx;
      }
      &-title {
        color: #1b2057;
        font-weight: bold;
        font-size: 44rpx;
        margin-bottom: 36rpx;
      }
      &-comma {
        margin-left: -40rpx;
      }
      &-content {
        position: relative;
        font-size: 28rpx;
        text-align: left;
        color: #333333;
        line-height: 40rpx;
        z-index: 2;
      }
      &-pic {
        position: absolute;
        right: 0;
        bottom: 0;
      }
    }
    .report-card {
      background-color: #ffffff;
      border-radius: 8px;
      padding: 32rpx 20rpx;
      margin-bottom: 16rpx;
      &-title {
        font-size: 32rpx;
        font-weight: 500;
        text-align: left;
        color: #333333;
        margin-bottom: 8px;
        position: relative;
        .text {
          position: relative;
          z-index: 2;
        }
        &::before {
          content: ""; // 必须要有内容，即使为空字符串
          position: absolute;
          left: -2rpx;
          top: -6rpx;
          z-index: 1;
          //   transform: translateY(-50%);
          width: 32rpx; // 图片的宽度
          height: 32rpx; // 图片的高度
          background-image: url(""); // 图片路径
          background-repeat: no-repeat;
          background-position: center;
          background-size: cover;
        }
      }
      .row {
        display: flex;
        margin-bottom: 24rpx;
        font-size: 28rpx;
        .title {
          white-space: nowrap;
          color: #999999;
          flex: 0 0 140rpx;
          width: 0;
        }
        .content {
          flex: 1;
          width: 0;
          color: #333333;
        }
      }
      .column {
        display: flex;
        flex-direction: column;
        // margin-bottom: 24rpx;
        .title {
          color: #999999;
          margin-bottom: 16rpx;
        }
        .content {
        }
      }
      & > .row:nth-last-child(1),
      & > .column:nth-last-child(1) {
        margin-bottom: 0;
      }
      .part-card {
        &-title {
          display: flex;
          margin-bottom: 20rpx;
          margin-top: 36rpx;
          .serial-num {
            margin-right: 16rpx;
          }
        }
        &-content {
          background-color: #f3f6f8;
          border-radius: 16rpx;
          padding: 0 20rpx;
          & > .row {
            padding: 20rpx 0;
            margin-bottom: 0;
            border-bottom: 1px dashed #cccccc;
            .title {
              flex: 0 0 92rpx;
              padding-right: 20rpx;
              box-sizing: border-box;
              text-align: center;
            }
          }
          & > .row:nth-last-child(1) {
            border-bottom: none;
          }
        }
      }
    }
  }
  &-info {
    color: #999999;
    font-size: 24rpx;
    line-height: 34rpx;
    text-align: left;
    width: 100%;
    padding: 16rpx 20rpx;
  }
  &-footer {
    width: 100%;
    height: 100rpx;
    .btn-box {
      height: 100rpx;
      width: 100%;
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 3;
      padding: 16rpx;
      box-sizing: border-box;
      background-color: #ffffff;
      .btn {
        width: 100%;
        height: 100%;
        background-color: #0091ff;
        border-radius: 8rpx;
        color: #ffffff;
        font-size: 28rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
        &-disabled {
          background-color: #cccccc;
          color: #ffffff;
        }
      }
    }
  }
}
.icon-close {
  display: inline-block;
  width: 24rpx; // 可以根据需要调整大小
  height: 24rpx;
  position: relative;
  cursor: pointer;
  color: #333;

  &::before,
  &::after {
    content: "";
    position: absolute;
    left: 50%;
    top: 50%;
    background-color: currentColor;
    width: 2rpx;
    height: 100%; // 可以根据需要调整比例
    transform-origin: center;
    transition: transform 0.2s ease-in-out;
  }

  &::before {
    transform: translate(-50%, -50%) rotate(45deg);
  }

  &::after {
    transform: translate(-50%, -50%) rotate(-45deg);
  }

  &:hover &::before,
  &:hover &::after {
    transform: translate(-50%, -50%) scale(1.2) rotate(45deg);
  }
}
image {
  height: auto;
}
.serial-num {
  width: 40rpx;
  line-height: 40rpx;
  height: 40rpx;
  text-align: center;
  background: #dcf0ff;
  border-radius: 4rpx;
  font-size: 24rpx;
  color: #0091ff;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.textarea-box {
  border: 2rpx solid #e9e9e9;
  padding: 10rpx;

  background-color: #ffffff;
  .length {
    text-align: right;
    // padding-bottom: 20rpx;
    color: #999999;
  }
}
.select-box {
  display: flex;
  flex-wrap: wrap;
  .select {
    flex: 0 0 calc(33.333% - 10rpx);
    width: 0;
    border: 2rpx solid #cccccc;
    padding: 4rpx 20rpx;
    box-sizing: border-box;
    color: #666666;
    margin-right: 10rpx;
    margin-bottom: 20rpx;
    border-radius: 8rpx;
    text-align: center;
    white-space: nowrap;
  }
  .selected {
    border-color: #0091ff;
    color: #0091ff;
  }
}
/deep/.img-upload-btn {
  background-color: #ffffff !important;
}
</style>